package com.itqf.realm;

import com.itqf.entity.SysUser;
import com.itqf.service.SysUsersService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author 徐老板
 * @date 2020/1/29   11:26
 */
@Component
public class UserRealm extends AuthorizingRealm {

    @Resource
    private SysUsersService sysUsersService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SysUser sysUser = (SysUser) principals.getPrimaryPrincipal();
        List<String> permsList = sysUsersService.findPermsByUID(sysUser.getUserId());
        List<String> roleList = sysUsersService.findRoleByUID(sysUser.getUserId());

        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
        info.addRoles(roleList);
        info.addStringPermissions(permsList);

        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken user = (UsernamePasswordToken) token;
        String username = user.getUsername();

        List<SysUser> sysUser = sysUsersService.findByName(username);
        SysUser shirologin=sysUser.get(0);

        if (shirologin==null){
            throw new UnknownAccountException("该用户不存在");
        }
        if (!shirologin.getPassword().equals(String.valueOf(user.getPassword()))){
            throw new IncorrectCredentialsException("密码输入错误");
        }
        if (shirologin.getStatus()==0){
            throw new LockedAccountException("用户被锁定");
        }
        SimpleAuthenticationInfo info=new SimpleAuthenticationInfo(shirologin,shirologin.getPassword() ,this.getName() );
        return info;
    }
}
